package com.wd.tech.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.google.gson.Gson;
import com.wd.tech.api.ApiService;
import com.wd.tech.app.App;
import com.wd.tech.bean.FindCommunityListBean;
import com.wd.tech.url.BaseUrl;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.FieldMap;
import retrofit2.http.HeaderMap;
import retrofit2.http.PartMap;
import retrofit2.http.QueryMap;

import static java.lang.String.valueOf;

/**
 * 时间：2020/7/1
 * 作者：徐黎明
 * 类的作用：工具类
 */
public class NetUtil {

    private final ApiService apiService;

    public NetUtil() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                //读取超时
                .readTimeout(5000, TimeUnit.SECONDS)
                //连接超时
                .connectTimeout(5000,TimeUnit.SECONDS)
                //读取超时
                .writeTimeout(5000,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                //日志拦截器
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public Response intercept(@NotNull Chain chain) throws IOException {
                        Request request=chain.request();
                        Request.Builder builder = request.newBuilder();
                        //添加请求头
                        SharedPreferences sharedPreferences= App.context.getSharedPreferences("login", Context.MODE_PRIVATE);
                        int userid = sharedPreferences.getInt("userid", 0);
                        String sessionid = sharedPreferences.getString("sessionid", "");
                        builder.addHeader("userid",userid+"");
                        builder.addHeader("sessionid",sessionid);
                        Log.e("userid",userid+"");
                        Log.e("sessionid",sessionid+"");
                        Request build = builder.build();
                        Log.d("xx", "intercept: "+build);
                        return chain.proceed(build);
                    }
                })
                .build();
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(BaseUrl.BASE_URL)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    private static class NetCall{
      private static NetUtil netUtil=new NetUtil();
    }

    public static NetUtil getInstance() {
        return NetCall.netUtil;
    }
    //接口回调
    public interface NetCallBack<T>{
        void success(T t);
        void Error(String error);
    }
    //判断是否有网
    public boolean HasNet(){
       ConnectivityManager manager = (ConnectivityManager) App.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
        if (activeNetworkInfo!=null&&activeNetworkInfo.isAvailable()){
            return true;
        }else {
            return false;
        }
    }
    //登录注册
    public void GetregisterInfo(String url, Map<String,Object> map,final Class cls,final NetCallBack callBack){
       apiService.GetRegisterInfo(url, map).subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .subscribe(new Observer<ResponseBody>() {
                   @Override
                   public void onSubscribe(Disposable d) {

                   }

                   @Override
                   public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                       try {
                           Object o = gson.fromJson(responseBody.string(), cls);
                           callBack.success(o);
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }

                   @Override
                   public void onError(Throwable e) {

                   }

                   @Override
                   public void onComplete() {

                   }
               });
    }

    //查询banner
    public void GetXBannerInfo(String url, final Class cls, final NetCallBack callBack){
        apiService.GetXBannerInfo(url).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //展示资讯首页
    public void GetNewsShow(String url, final Class cls, Map<String ,Object>map, final NetCallBack callBack){
        apiService.GetNewsSh(url,map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //兴趣频道
    public void GetChannel(String url, final Class cls, final NetCallBack callBack){
        apiService.GetChannel(url).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //频道详情
    public void GetNewsChanner(String url, final Class cls, Map<String ,Object>map, final NetCallBack callBack){
        apiService.GetNewsSh(url,map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }



    //社区列表
    public void GetcommunityInfo(String url, Map<String, Object> map,final Class cls, final NetCallBack callBack){
        apiService.GetCommunityInfo(url,map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //点赞
    public void AddCommunity(String url,Map<String, Object> map,final Class cls, final NetCallBack callBack){
        apiService.AddCommunity(url,map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String string = responseBody.string();
                            Object o = new Gson().fromJson(string, cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //发布帖子
    public void ReleasePost(String url, Map<String, RequestBody> map, final Class cls, final NetCallBack callBack){
        apiService.ReleasePost(url,map).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(), cls);
                            callBack.success(o);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

//    public void CancelAdd(String url, Map<String, Object> map, final Class cls, final NetCallBack callBack){
//        apiService.CancelAdd(url,map).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<ResponseBody>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(ResponseBody responseBody) {
//                        try {
//                            String string = responseBody.string();
//                            Object o = new Gson().fromJson(string, cls);
//                            callBack.success(o);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
//    }

}
